package com.v1.video.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.Mode;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXVideoObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.adapter.AdImageAdapter;
import com.v1.video.adapter.CommentAdapter;
import com.v1.video.adapter.DanmuAdapter;
import com.v1.video.domain.CarouselInfo4;
import com.v1.video.domain.CommentEntity;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.RequestData;
import com.v1.video.domain.ResultInfoEntity;
import com.v1.video.domain.SecondVideoDetailInfo;
import com.v1.video.domain.SecondVideoDetailInfo.SecondVideoDetailInfoBody;
import com.v1.video.domain.SecondVideoDetailInfo.SpeciaComment;
import com.v1.video.domain.SecondVideoDetailInfo.SpeciaComment.User;
import com.v1.video.domain.SecondVideoDetailInfo.VoteInfo;
import com.v1.video.domain.VideoAdEntity;
import com.v1.video.domain.VideoCollectionInfoEntity;
import com.v1.video.engine.NetEngine;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.ParamList;
import com.v1.video.httpmanager.ParamList.Parameter;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.interfaces.CommentDataCallBack;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;
import com.v1.video.util.PopupWindowUtils;
import com.v1.video.util.PopupWindowUtils.OnActionSheetItemClick;
import com.v1.video.util.Utils;
import com.v1.video.view.CircleFlowIndicator;
import com.v1.video.view.CommentEditFragment;
import com.v1.video.view.CustomShareSheetDialog;
import com.v1.video.view.DanmuView;
import com.v1.video.view.NoScrollListView;
import com.v1.video.view.ViewFlow;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.qzone.QZone;

/**
 * 秒评详情
 * 
 * @author wangfang
 * 
 */
public class SecondVideoDetailActivity2 extends BaseVideoPlayActivity {

	private View mViewHeader, mVadLine;
	private PullToRefreshListView mRefreshListView;
	// 专家评论
	private NoScrollListView headerListView;
	private HeaderListAdapter headerListAdapter;
	private List<SpeciaComment> headerSpeciaComments = new ArrayList<SecondVideoDetailInfo.SpeciaComment>();

	private ListView mListView;
	private ViewFlow mViewflow;
	private LinearLayout bottomLayout;
	private int mScreenWidth;
	private int mScreenHeight;
	private CircleFlowIndicator mFlowIndicator;
	private RelativeLayout mLayAd;
	private TextView mTvRecommendnum;
	private CommentEditFragment mCommentEditFragment;
	private CommentAdapter mAdapter;
	private AdImageAdapter mImageAdapter;
	private int mCurIndex = 0;
	private String mSid;
	private String mLastId = "0";
	private String mCommentId;
	private String mReplyName;
	private TextView tvTitle, tvPlayNum, tvContent;
	private ImageView ivMore;
	private PopupWindow mPopupWindow;
	private IWXAPI mWxApi;
	private SecondVideoDetailInfoBody mSecondVideoDetailInfo;
	private ImageView mIvCollection;
	private String mCommentState = Constant.COMMENT_TIME_SORT;
//	private Button mBtnHot, mBtnNew;

	// 彈幕
	private DanmuView mDanmuView;
	private DanmuAdapter mDanmuAdapter;
	private ImageView ivDanmuSwitch;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_secondvideodetail);
	}

	@Override
	protected void initView() {
		super.initView();
		mViewHeader = getLayoutInflater().inflate(
				R.layout.activity_secondvideodetail_header2, null);
		mRefreshListView = (PullToRefreshListView) findViewById(R.id.second_listView);
		tvTitle = (TextView) mViewHeader.findViewById(R.id.tv_title);
		tvPlayNum = (TextView) mViewHeader.findViewById(R.id.tv_playnum);
		tvContent = (TextView) mViewHeader.findViewById(R.id.tv_content);
		ivMore = (ImageView) mViewHeader.findViewById(R.id.iv_more);
		headerListView = (NoScrollListView) mViewHeader
				.findViewById(R.id.lv_expert);
		bottomLayout = (LinearLayout) findViewById(R.id.video_playdetail_bottom);
		mListView = mRefreshListView.getRefreshableView();
		mRefreshListView.setMode(Mode.PULL_FROM_START);
		mListView.addHeaderView(mViewHeader);
		mViewflow = (ViewFlow) mViewHeader.findViewById(R.id.vf_viewflow);
		mFlowIndicator = (CircleFlowIndicator) mViewHeader
				.findViewById(R.id.flowIndicator);
		mLayAd = (RelativeLayout) mViewHeader.findViewById(R.id.lay_ad);
		mScreenHeight = Utils.getScreenHeight(this);
		mScreenWidth = Utils.getScreenWidth(this);
		int height = (int) (mScreenWidth * 5 / 16);
		LayoutParams param = mLayAd.getLayoutParams();
		param.height = height;
		param.width = mScreenWidth;
		mLayAd.setLayoutParams(param);
		mLayAd.setVisibility(View.GONE);
		mVadLine = mViewHeader.findViewById(R.id.v_adline);
		mVadLine.setVisibility(View.GONE);
		mTvRecommendnum = (TextView) mViewHeader
				.findViewById(R.id.tv_recommendnum);
		mIvCollection = (ImageView) findViewById(R.id.iv_collection);
//		mBtnNew = (Button) mViewHeader.findViewById(R.id.btn_new);
//		mBtnHot = (Button) mViewHeader.findViewById(R.id.btn_hot);
		//		ivDanmuSwitch = (ImageView) findViewById(R.id.iv_barrage);
		initDamukaView();
		rl_unsupport = findViewById(R.id.rl_unsupport);
		ll_support = findViewById(R.id.ll_support);
		view_vote = findViewById(R.id.view_vote);
		ll_speclist_recommend = mViewHeader.findViewById(R.id.ll_speclist_recommend);
		tv_unsupport_left_content = (TextView) mViewHeader.findViewById(R.id.tv_unsupport_left_content);
		tv_unsupport_right_content = (TextView)mViewHeader. findViewById(R.id.tv_unsupport_right_content);
		tv_support_left_content = (TextView)mViewHeader. findViewById(R.id.tv_support_left_content);
		tv_support_right_content = (TextView)mViewHeader. findViewById(R.id.tv_support_right_content);
		tv_result_left_content = (TextView)mViewHeader. findViewById(R.id.tv_result_left_content);
		tv_result_right_content = (TextView)mViewHeader. findViewById(R.id.tv_result_right_content);
		item_vote_progressbar = (ProgressBar)mViewHeader. findViewById(R.id.item_vote_progressbar);
		view_vote_line = mViewHeader. findViewById(R.id.view_vote_line);
		line_sperecommend = mViewHeader. findViewById(R.id.line_sperecommend);
	}

	@Override
	protected void initData() {
		super.initData();
		mWxApi = WXAPIFactory.createWXAPI(this, Constant.APP_ID);
		mWxApi.registerApp(Constant.APP_ID);
		mAdapter = new CommentAdapter(this, CommentAdapter.SECOND_FLAG);
		mListView.setAdapter(mAdapter);

		headerListAdapter = new HeaderListAdapter();
		headerListView.setAdapter(headerListAdapter);
		Intent intent = getIntent();
		mSid = intent.getStringExtra("sid");
		getVideoDetail(mSid);
	}

	@Override
	protected void handlePlayerPortrait() {
		super.handlePlayerPortrait();
		if (bottomLayout != null) {
			bottomLayout.setVisibility(View.VISIBLE);
		}
	}

	@Override
	protected void handlePlayerLandscape() {
		super.handlePlayerLandscape();
		if (bottomLayout != null) {
			bottomLayout.setVisibility(View.GONE);
		}
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	protected void setListener() {
		super.setListener();
		ivMore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (tvContent.getVisibility() == View.GONE) {
					tvContent.setVisibility(View.VISIBLE);
					ivMore.setRotation(180);
				} else {
					tvContent.setVisibility(View.GONE);
					ivMore.setRotation(0);
				}
			}
		});
		findViewById(R.id.iv_share).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				int height = mScreenHeight
						- (int) (mScreenWidth * 9 / 16)
						- Utils.getStatusBarHeight(SecondVideoDetailActivity2.this);
				mPopupWindow = PopupWindowUtils.getInstance().sharePopupWindow(
						SecondVideoDetailActivity2.this, v, height,
						new OnActionSheetItemClick() {

							@Override
							public void onClick(int index, String actionName) {
								// TODO Auto-generated method stub
								switch (index) {
								case CustomShareSheetDialog.TYPE_WEIXIN_MOMENTS:
									if (mWxApi.isWXAppInstalled()) {
										onkeyshareWeiXin(0);
									} else {
										showToast("亲，您尚未安装微信客户端，请下载安装~");
									}
									break;
								case CustomShareSheetDialog.TYPE_WEIXIN:
									if (mWxApi.isWXAppInstalled()) {
										onkeyshareWeiXin(1);
									} else {
										showToast("亲，您尚未安装微信客户端，请下载安装~");
									}
									break;
								case CustomShareSheetDialog.TYPE_QQ:
									onkeyshareQQ(ShareSDK.getPlatform(
											SecondVideoDetailActivity2.this,
											QQ.NAME));
									break;
								case CustomShareSheetDialog.TYPE_QQ_SPACE:
									onkeyshareQQ(ShareSDK.getPlatform(
											SecondVideoDetailActivity2.this,
											QZone.NAME));
									break;
								case CustomShareSheetDialog.TYPE_SINA_WEIBO:
									showSharedDialog(
											SecondVideoDetailActivity2.this, 0);
									break;
								case CustomShareSheetDialog.TYPE_COPY:
									if (mSecondVideoDetailInfo != null
									&& mSecondVideoDetailInfo
									.getVideo() != null) {
										ClipboardManager c = (ClipboardManager) SecondVideoDetailActivity2.this
												.getSystemService(Context.CLIPBOARD_SERVICE);
										if (!TextUtils
												.isEmpty(mSecondVideoDetailInfo
														.getShareUrl())) {
											c.setPrimaryClip(ClipData
													.newPlainText(
															"url",
															mSecondVideoDetailInfo
															.getShareUrl()));
										} else {
											c.setPrimaryClip(ClipData
													.newPlainText("url",
															mSecondVideoDetailInfo
															.getVideo()
															.getUrl()));
										}
										showToast("复制成功");
									} else {
										showToast("未获取到分享内容");
									}
									break;
								default:
									break;
								}
							}

						});
			}
		});
		findViewById(R.id.tv_sendcomment).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						showSendCommentDialog("", "");
					}
				});
		mIvCollection.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(LoginInfo.getInstance().isLogin()){
					setVideoCollection();
				} else {
					transferLogin(0);
				}
			}
		});

//		mBtnNew.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				if (!Constant.COMMENT_TIME_SORT.equals(mCommentState)) {
//					mCommentState = Constant.COMMENT_TIME_SORT;
//					mBtnNew.setBackgroundResource(R.drawable.shape_new_seclect_bg);
//					mBtnNew.setTextColor(SecondVideoDetailActivity2.this
//							.getResources().getColor(R.color.white));
//					mBtnHot.setBackgroundResource(R.drawable.shape_hot_normal_bg);
//					mBtnHot.setTextColor(SecondVideoDetailActivity2.this
//							.getResources().getColor(R.color.color_666666));
//					if (mRefreshListView != null) {
//						mRefreshListView.doPullRefreshing(50);
//					}
//				}
//			}
//		});
//
//		mBtnHot.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				// TODO Auto-generated method stub
//				if (!Constant.COMMENT_HOT_SORT.equals(mCommentState)) {
//					mCommentState = Constant.COMMENT_HOT_SORT;
//					mBtnNew.setBackgroundResource(R.drawable.shape_new_normal_bg);
//					mBtnNew.setTextColor(SecondVideoDetailActivity2.this
//							.getResources().getColor(R.color.color_666666));
//					mBtnHot.setBackgroundResource(R.drawable.shape_hot_seclect_bg);
//					mBtnHot.setTextColor(SecondVideoDetailActivity2.this
//							.getResources().getColor(R.color.white));
//					if (mRefreshListView != null) {
//						mRefreshListView.doPullRefreshing(50);
//					}
//				}
//			}
//		});
		mRefreshListView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				mCurIndex = 0;
				mLastId = "0";
				if (Helper.checkConnection(SecondVideoDetailActivity2.this)) {
					getCommentData();
				} else {
					mHandler.sendEmptyMessageDelayed(0, 100);
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				if (Helper.checkConnection(SecondVideoDetailActivity2.this)) {
					getCommentData();
				} else {
					mHandler.sendEmptyMessageDelayed(0, 100);
				}
			}
		});

		tv_unsupport_left_content.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				detailVote("1");
			}
		});

		tv_unsupport_right_content.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				detailVote("2");
			}
		});
	}
	private void detailVote(final String action){
		ParamList param = new ParamList();
		param.add(new Parameter("devid",Constant.DEVICEID));
		param.add(new Parameter("version",Constant.PRODUCT_VERSION));
		param.add(new Parameter("pcode",Constant.PRODUCT_CODE));
		param.add(new Parameter("action",action));
		param.add(new Parameter("contentId",mSid));
		RequestManager.getInstance().postRequest(SecondVideoDetailActivity2.this, Constant.SECOND_DETAIL_VOTE, param, "second_detail_vote", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,
					String keyId) {
				// TODO Auto-generated method stub
				rl_unsupport.setVisibility(View.GONE);
				ll_support.setVisibility(View.VISIBLE);
				if(!TextUtils.isEmpty(voteInfo.getSupport_text())){
					tv_support_left_content.setText(voteInfo.getSupport_text());
				}else{
					tv_support_left_content.setText("");
				}

				if(!TextUtils.isEmpty(voteInfo.getOppose_text())){
					tv_support_right_content.setText(voteInfo.getOppose_text());
				}else{
					tv_support_right_content.setText("");
				}
				int oppseNum = voteInfo.getOppose();
				int supportNUm = voteInfo.getSupport();
				if(action.equals("1")){
					supportNUm = supportNUm+1;
				}else{
					oppseNum = oppseNum+1;
				}
				double k = (double) supportNUm / (oppseNum+supportNUm) * 100;
				BigDecimal big = new BigDecimal(k);
				int percent_int = big.setScale(2, BigDecimal.ROUND_HALF_UP).intValue();
				String percent = percent_int + "%";
				int oppsePircent = 100 - percent_int;
				tv_result_left_content.setText(supportNUm+""+"("+percent+")");
				tv_result_right_content.setText(oppseNum+""+"("+oppsePircent+"%"+")");
				item_vote_progressbar.setProgress(percent_int);
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub

			}

		});
	}
	private VoteInfo voteInfo;
	// 初始化
	private void initDamukaView() {
		//		mDanmuView = (DanmuView) findViewById(R.id.sv_danmuview);
		//		mDanmuAdapter = new DanmuAdapter(this, mDanmuView);
		//		mDanmuView.setAdapter(mDanmuAdapter);
	}

	/***
	 * 获取视频详情
	 * 
	 * @param videoId
	 */
	private void getVideoDetail(String videoId) {
		waitingLl.setVisibility(View.VISIBLE);
		String url = String.format(V1VideoHttpApi.SECOND_COMMENT_DETAIL(),
				Constant.DEVICEID, videoId);
		Logger.i(TAG, "详情页Url =" + url);
		RequestManager.getInstance().getRequest(SecondVideoDetailActivity2.this,
				url, null, SecondVideoDetailInfo.class, 0,
				"VideoPlayDetailActivity", new OnResponseListener() {

			@Override
			public void onSuccess(Object object, int code,
					String message, String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object=" + object.toString());
				if (object != null) {
					SecondVideoDetailInfo entity = (SecondVideoDetailInfo) object;
					if (entity.getBody() != null
							&& "1".equals(entity.getBody().getCode())) {
						mSecondVideoDetailInfo = entity.getBody();
						if(mSecondVideoDetailInfo.getVote() != null){
							voteInfo = mSecondVideoDetailInfo.getVote();
							if(voteInfo.getShowbar().equals("1")){
								view_vote.setVisibility(View.VISIBLE);
								view_vote_line.setVisibility(View.VISIBLE);
								showVote(voteInfo);
							}else{
								view_vote.setVisibility(View.GONE);
								view_vote_line.setVisibility(View.GONE);
							}
						}
						processVideoDetail(entity, 0);
						getCommentData();
//						getCarouselData();
						getVideoCollection();
					} else {
						toast(entity.getBody().getMsg());
					}
				}
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
				//						finish();
			}
		});
	}

	private void processVideoDetail(SecondVideoDetailInfo VideoPageInfo,
			int type) {
		if (VideoPageInfo != null && Constant.CODE_RESULT_SUCCESS == type) {
			Logger.i(TAG, "成功加载了！！");
			SecondVideoDetailInfo.VideoDetail videoInfo = VideoPageInfo
					.getBody().getVideo();
			tvTitle.setText(videoInfo.getTitle());
			tvPlayNum.setText("播放:" + videoInfo.getPlayCount() + "次");
			if (!TextUtils.isEmpty(videoInfo.getDescription())) {
				tvContent.setText(videoInfo.getDescription());
			}
			if(VideoPageInfo.getBody().getList() != null && VideoPageInfo.getBody().getList().size()>0){
				ll_speclist_recommend.setVisibility(View.VISIBLE);
				line_sperecommend.setVisibility(View.VISIBLE);
				headerSpeciaComments.addAll(VideoPageInfo.getBody().getList());
			}else{
				ll_speclist_recommend.setVisibility(View.GONE);
				line_sperecommend.setVisibility(View.GONE);
			}

			headerListAdapter.notifyDataSetChanged();

			String path = videoInfo.getUrl();
			setVideoPath(path);
		}
	}

	private void showVote(VoteInfo voteInfo){
		if(!TextUtils.isEmpty(voteInfo.getSupport_text())){
			tv_unsupport_left_content.setText(voteInfo.getSupport_text());
		}else{
			tv_unsupport_left_content.setText("");
		}

		if(!TextUtils.isEmpty(voteInfo.getOppose_text())){
			tv_unsupport_right_content.setText(voteInfo.getOppose_text());
		}else{
			tv_unsupport_right_content.setText("");
		}

	}

	private void getCarouselData() {
		String url = String.format(V1VideoHttpApi.ADVERTISEMENT_LIST(), "1");
		Logger.i(TAG, "获取广告url=" + url);
		RequestManager.getInstance().getRequest(this, url, VideoAdEntity.class,
				new OnResponseListener() {

			@Override
			public void onSuccess(Object object, int code,
					String message, String keyId) {
				// TODO Auto-generated method stub
				try {
					if (object != null) {
						VideoAdEntity entity = (VideoAdEntity) object;
						if (entity != null && entity.getBody() != null
								&& entity.getBody().getData() != null) {
							showViewFlow(entity.getBody().getData()
									.getCarousels());
						} else {
							hideViewFlow();
						}
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.e(TAG, message);
				hideViewFlow();
			}

		});
	}

	/**
	 * 显示轮播图
	 */
	private void showViewFlow(List<CarouselInfo4> lstCarousel) {
		if (lstCarousel != null && lstCarousel.size() > 0) {
			try {
				mImageAdapter = new AdImageAdapter(this);
				mImageAdapter.setLstData(lstCarousel);
				mViewflow.setAdapter(mImageAdapter);
				mViewflow.setmSideBuffer(lstCarousel.size());
				mViewflow.setFlowIndicator(mFlowIndicator);
				if (lstCarousel.size() > 1) {
					mViewflow.setSelection(lstCarousel.size() * 1000); // 设置初始位置
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} else {
			hideViewFlow();
		}
	}

	private void hideViewFlow() {
		mVadLine.setVisibility(View.GONE);
		mLayAd.setVisibility(View.GONE);
	}

	private void getCommentData() {
		if (mSecondVideoDetailInfo == null
				|| mSecondVideoDetailInfo.getVideo() == null) {
			return;
		}
		String id = mSecondVideoDetailInfo.getVideo().getId();
		new NetEngine().getCommentData(this, id, mLastId,
				Constant.COMMENT_VIDEO_TYPE, mCommentState,
				new OnResponseListener() {

			@Override
			public void onSuccess(Object object, int code,
					String message, String keyId) {
				// TODO Auto-generated method stub
				mRefreshListView.onRefreshComplete();
				try {
					if (object != null) {
						CommentEntity entity = (CommentEntity) object;
						if (entity != null
								&& entity.getBody() != null
								&& entity.getBody().getComments_list() != null
								&& entity.getBody().getComments_list()
								.size() > 0) {
							mLastId = entity.getBody().getLast_id();
							if (mAdapter != null) {
								if (mCurIndex == 0) {
									if(entity.getBody()
											.getComments_list()!= null && entity.getBody()
											.getComments_list().size()>0){
										mTvRecommendnum.setText(entity.getBody()
												.getComments_list().size() + "");
									}

									mAdapter.getDataLst().clear();
								}
								mAdapter.setDataList(entity.getBody()
										.getComments_list());
							}
							if (mDanmuAdapter != null) {
								mDanmuAdapter.addDataList(entity
										.getBody().getComments_list());
							}
							int total = (mCurIndex + 1)
									* Constant.COMMENT_PAGE_SIZE;
							if (total < entity.getBody().getTotal()) {
								mCurIndex++;
								if (mRefreshListView != null) {
									mRefreshListView
									.setMode(PullToRefreshBase.Mode.BOTH);
								}
							} else {
								if (mRefreshListView != null) {
									mRefreshListView
									.setMode(PullToRefreshBase.Mode.DISABLED);
								}
							}
						} else {
							mTvRecommendnum.setText("");
							mAdapter.setNoComment(true);
						}
					} else {
						mTvRecommendnum.setText("");
						mAdapter.setNoComment(true);
					}
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}

			@Override
			public void onFailure(int code, String message) {
				mRefreshListView.onRefreshComplete();
				Logger.e(TAG, message);
			}

		});
	}
	
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what){
			case 200:
				getCommentData();
				break;
			}
		}
	};
		

	public void showSendCommentDialog(String id, String nickname) {
		if (LoginInfo.getInstance().isLogin()) {
			if (mCommentEditFragment == null) {
				mCommentEditFragment = new CommentEditFragment(this,
						new CommentDataCallBack() {
					@Override
					public void notifyData() {
						if (mRefreshListView != null) {
//							mRefreshListView.doPullRefreshing(50);
//							Message msg = Message.obtain();
//							msg.what=200;
//							handler.sendMessageDelayed(msg, 200);
							mCurIndex = 0;
							mLastId = "0";
							getCommentData();
							
						}
					}

					@Override
					public String getObjectId() {
						if (mSecondVideoDetailInfo != null
								&& mSecondVideoDetailInfo.getVideo() != null) {
							return mSecondVideoDetailInfo.getVideo()
									.getId();
						}
						return "";
					}

					@Override
					public String getObjectName() {
						if (mSecondVideoDetailInfo != null
								&& mSecondVideoDetailInfo.getVideo() != null) {
							return mSecondVideoDetailInfo.getVideo()
									.getTitle();
						}
						return "";
					}
				});
			}
			mCommentEditFragment.showCommentDialog(id, nickname,
					Constant.COMMENT_VIDEO_TYPE);
		} else {
			mCommentId = id;
			mReplyName = nickname;
			transferLogin(Constant.REQUEST_COMMENT_CODE);
		}
	}

	private void transferLogin(int requestCode) {
		Intent intent = new Intent(this, SettingLoginActivity.class);
		intent.putExtra("loginFlag", 2);
		startActivityForResult(intent, requestCode);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case Constant.REQUEST_COMMENT_CODE:
			if (LoginInfo.getInstance().isLogin()) {
				showSendCommentDialog(mCommentId, mReplyName);
			}
			break;
		default:
			break;
		}
	}

	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:
				if (mRefreshListView != null) {
					mRefreshListView.onRefreshComplete();
				}
				showToast(R.string.net_no_click);
				break;
			default:
				break;
			}
		}
	};
	private TextView tv_unsupport_left_content;
	private TextView tv_unsupport_right_content;
	private TextView tv_support_left_content;
	private TextView tv_support_right_content;
	private TextView tv_result_left_content;
	private TextView tv_result_right_content;
	private ProgressBar item_vote_progressbar;
	private View rl_unsupport;
	private View ll_support;
	private View view_vote;
	private View ll_speclist_recommend;
	private View view_vote_line;
	private View line_sperecommend;

	public class HeaderListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return headerSpeciaComments.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			if(convertView == null){
				convertView =View.inflate(SecondVideoDetailActivity2.this,
						R.layout.item_specialist_commend, null);
				holder = new ViewHolder();
//				holder.img_specialist = (ImageView) convertView.findViewById(R.id.img_specialist);
				holder.tv_specialist_name = (TextView) convertView.findViewById(R.id.tv_specialist_name);
//				holder.tv_praise_num = (TextView) convertView.findViewById(R.id.tv_praise_nume);
//				holder.tv_unpraise_num = (TextView) convertView.findViewById(R.id.tv_unpraise_nume);
				holder.tv_specialist_comment = (TextView) convertView.findViewById(R.id.tv_specialist_comment);
				holder.tv_specialist_time = (TextView) convertView.findViewById(R.id.tv_specialist_time);
//				holder.ll_praise = convertView.findViewById(R.id.ll_praise);
//				holder.ll_unpraise =convertView.findViewById(R.id.ll_unpraise);
				convertView.setTag(holder);
			}else{
				holder= (ViewHolder) convertView.getTag();
			}


			if(headerSpeciaComments != null && headerSpeciaComments.size()>0){
				final SpeciaComment speciaComment = headerSpeciaComments.get(position);

				if(speciaComment.getUser() != null){
					User user = speciaComment.getUser();
					if(!TextUtils.isEmpty(user.getNickname())){
						holder.tv_specialist_name.setText(user.getNickname());
					}else{
						holder.tv_specialist_name.setText(user.getNickname());
					}

//					ImageLoader.getInstance().displayImage(user.getHeadpic(),
//							holder.img_specialist, Constant.IMAGE_OPTIONS_FOR_USER_OTHER, new SimpleImageLoadingListener() {
//
//						public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
//							if(loadedImage!=null){
//								ImageView iv = (ImageView) view;
//								iv.setImageBitmap(Utils.toRoundBitmap(loadedImage));
//							}
//						}
//
//					});
				}
//				if(!TextUtils.isEmpty(speciaComment.getIs_support()) && speciaComment.getIs_support().equals("0")){
//					if(!TextUtils.isEmpty(speciaComment.getContent())){
//						
//						holder.tv_specialist_comment.setText(Html.fromHtml("<font color='#666666'>"+"#"+speciaComment.getOppose_text()+"#"+"  "+"</font>"+speciaComment.getContent()));
//					}else{
//						holder.tv_specialist_comment.setText("");
//					}
//				}else{
//					holder.tv_specialist_comment.setText(Html.fromHtml("<font color='#666666'>"+"#"+speciaComment.getSupport_text()+"#"+"   "+"</font>"+speciaComment.getContent()));
//				}
				
				if(!TextUtils.isEmpty(speciaComment.getContent())){
					
					holder.tv_specialist_comment.setText(speciaComment.getContent());
				}else{
					holder.tv_specialist_comment.setText("");
				}

//				if(!TextUtils.isEmpty(speciaComment.getOppose())){
//					holder.tv_unpraise_num.setText(speciaComment.getOppose());
//				}else{
//					holder.tv_unpraise_num.setText("");
//				}
//
//				if(!TextUtils.isEmpty(speciaComment.getSupport())){
//					holder.tv_praise_num.setText(speciaComment.getSupport());
//				}else{
//					holder.tv_praise_num.setText("");
//				}

				Calendar c = Calendar.getInstance();
				String myear =String.valueOf( c.get(Calendar.YEAR));
				if(!TextUtils.isEmpty(speciaComment.getPubTime())){
					String data_year = speciaComment.getPubTime().substring(0, 4);
					String pubTime = "";
					if(myear.equals(data_year)){
						pubTime = speciaComment.getPubTime().substring(5,10);
					}else{
						pubTime = speciaComment.getPubTime().substring(0,10);
					}
					holder.tv_specialist_time.setText(pubTime);
				}else{
					holder.tv_specialist_time.setText("");
				}

//				holder.ll_praise.setOnClickListener(new OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//					int praise_num =Integer.valueOf(speciaComment.getSupport());
//					praise_num= praise_num+1;
//					holder.tv_praise_num.setText(praise_num+"");
//						requestVote(speciaComment.getContentId(), 1);
//					}
//				});
//				holder.ll_unpraise.setOnClickListener(new OnClickListener() {
//
//					@Override
//					public void onClick(View v) {
//						int oppose_num =Integer.valueOf(speciaComment.getOppose());
//						oppose_num= oppose_num+1;
//						holder.tv_unpraise_num.setText(oppose_num+"");
//						requestVote(speciaComment.getContentId(), 2);
//					}
//				});
			}
			return convertView;
		}

	}
	private class ViewHolder{
		ImageView img_specialist;
		TextView tv_specialist_name,tv_specialist_comment,tv_specialist_time;
//		View ll_praise,ll_unpraise;
	}

	/**
	 * 1:赞;2:踩
	 * 
	 * @param action
	 */
	private void requestVote(String contentid, int action) {
		String uid = LoginInfo.getInstance().getUserId();
		if (TextUtils.isEmpty(uid))
			uid = "";
		String url = String.format(V1VideoHttpApi.SECOND_COMMENT_VOTE(),
				Constant.DEVICEID, uid, contentid, "" + action);
		Logger.i(TAG, "投票Url =" + url);
		RequestManager.getInstance().getRequest(this, url, RequestData.class,
				new OnResponseListener() {

			@Override
			public void onSuccess(Object object, int code,
					String message, String keyId) {
				if (object != null) {
					RequestData requestData = (RequestData) object;
					String msg = requestData.getBody().getMsg();
//					showToast(msg);
				}
			}

			@Override
			public void onFailure(int code, String message) {

			}
		});
	}

	/** 查询视频是否收藏 */
	private void getVideoCollection() {
		if (mSecondVideoDetailInfo == null
				|| mSecondVideoDetailInfo.getVideo() == null) {
			return;
		}
		String videoId = mSecondVideoDetailInfo.getVideo().getId();
		String url = V1VideoHttpApi.GET_QUERY_VIDEO_COLLECTED() + "&devid="
				+ Constant.DEVICEID + "&vid=" + videoId + "&uid="
				+ LoginInfo.getInstance().getUserId();
		Logger.i(TAG, "收藏url==" + url);
		RequestManager.getInstance().getRequest(this, 1, url, null,
				VideoCollectionInfoEntity.class, 0, "PaikeVideoDetailActivity",
				new OnResponseListener() {

			@Override
			public void onSuccess(Object object, int code,
					String message, String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object=" + object.toString());
				if (object != null) {
					VideoCollectionInfoEntity entity = (VideoCollectionInfoEntity) object;
					if (entity != null && entity.getBody() != null
							&& entity.getBody().getResult() != null) {
						if (Constant.RESULT_CODE_SUCCESS.equals(entity
								.getBody().getResult().getCode())) {
							if ("0".equals(entity.getBody().getState())) {// 未收藏
								isCollect = false;
								mIvCollection
								.setImageResource(R.drawable.second_collect);
							} else {// 已收藏
								isCollect = true;
								mIvCollection
								.setImageResource(R.drawable.second_collect_press);
							}
						}
					}
				}
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
			}
		});
	}

	/**
	 * 视频收藏或取消收藏
	 */
	private void setVideoCollection() {
		if (mSecondVideoDetailInfo == null
				|| mSecondVideoDetailInfo.getVideo() == null) {
			return;
		}
		String videoId = mSecondVideoDetailInfo.getVideo().getId();
		String url = "";
		if (isCollect) {
			url = V1VideoHttpApi.GET_CANCELL_COLLECTION_VIDEO() + "&devid="
					+ Constant.DEVICEID;
		} else {
			url = V1VideoHttpApi.GET_COLLECTION_VIDEO() + "&devid=" + Constant.DEVICEID;
		}
		ParamList list = new ParamList();
		list.add(new Parameter("vid", videoId));
		list.add(new Parameter("stype", "1"));
		list.add(new Parameter("uid", LoginInfo.getInstance().getUserId()));
		RequestManager.getInstance().getRequest(this, 1, url, list,
				ResultInfoEntity.class, 0, "PaikeVideoDetailActivity",
				new OnResponseListener() {

			@Override
			public void onSuccess(Object object, int code,
					String message, String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object=" + object.toString());
				if (object != null) {
					ResultInfoEntity entity = (ResultInfoEntity) object;
					if (entity != null && entity.getBody() != null
							&& entity.getBody().getResult() != null) {
						if (Constant.RESULT_CODE_SUCCESS.equals(entity
								.getBody().getResult().getCode())) {
							String text = "";
							if (isCollect) {
								isCollect = false;
								mIvCollection
								.setImageResource(R.drawable.second_collect);
								text = "取消收藏";
							} else {
								isCollect = true;
								mIvCollection
								.setImageResource(R.drawable.second_collect_press);
								text = "收藏成功";
							}
							Utils.showToast(
									SecondVideoDetailActivity2.this,
									text, 1);
						} else {
							Utils.showToast(
									SecondVideoDetailActivity2.this,
									entity.getBody().getResult()
									.getMessage(), 1);
						}
					}
				}
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
			}
		});
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mPopupWindow != null) {
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			}
			mPopupWindow = null;
		}
	}

	@Override
	protected void onThePrepared(MediaPlayer mp) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onTheBufferingUpdate(MediaPlayer mp, int percent) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onTheCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onTheError(MediaPlayer mp, int what, int extra) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onTheSeekComplete(MediaPlayer mp) {
		// TODO Auto-generated method stub

	}

	/** 分享到微信0:朋友圈，1 微信好友 */
	private void onkeyshareWeiXin(int type) {
		if (mSecondVideoDetailInfo != null
				&& mSecondVideoDetailInfo.getVideo() != null) {
			WXVideoObject video = new WXVideoObject();
			if (!TextUtils.isEmpty(mSecondVideoDetailInfo.getShareUrl())
					&& mSecondVideoDetailInfo.getShareUrl().length() > 6) {
				video.videoUrl = mSecondVideoDetailInfo.getShareUrl();
			} else {
				video.videoUrl = Constant.PAIKE_VIDEO_SHARE_URL
						+ mSecondVideoDetailInfo.getVideo().getPic()
						+ "&videoURL="
						+ mSecondVideoDetailInfo.getVideo().getUrl();
			}
			String content = "\""
					+ mSecondVideoDetailInfo.getVideo().getTitle()
					+ "\""
					+ "点此播放"
					+ "\""
					+ video.videoUrl
					+ "\""
					+ "（通过＃第一视频＃分享，@第一视频，聚合全球海量有趣有料有用的精选短视频，助你大开眼界！下载猛戳http://apps.v1.cn）";
			WXMediaMessage msg = new WXMediaMessage(video);
			msg.title = mSecondVideoDetailInfo.getVideo().getTitle();
			msg.description = content;
			Bitmap thumb = BitmapFactory.decodeResource(getResources(),
					R.drawable.ic_launcher);
			msg.thumbData = com.v1.video.util.Util.bmpToByteArray(thumb, true);
			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = buildTransaction("video");
			req.message = msg;
			req.scene = (type == 0 ? SendMessageToWX.Req.WXSceneTimeline
					: SendMessageToWX.Req.WXSceneSession);
			mWxApi.sendReq(req);
			Constant.setShare(true);
			Constant.listenerShare.init(this, null);
		} else {
			showToast("未获取到分享内容");
		}
	}

	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis())
				: type + System.currentTimeMillis();
	}

	/**
	 * QQ空间和QQ
	 * 
	 * @param plat
	 */
	private void onkeyshareQQ(Platform plat) {
		if (mSecondVideoDetailInfo != null
				&& mSecondVideoDetailInfo.getVideo() != null) {
			String url = "";
			if (!TextUtils.isEmpty(mSecondVideoDetailInfo.getShareUrl())
					&& mSecondVideoDetailInfo.getShareUrl().length() > 6) {
				url = mSecondVideoDetailInfo.getShareUrl();
			} else {
				url = Constant.PAIKE_VIDEO_SHARE_URL
						+ mSecondVideoDetailInfo.getVideo().getPic()
						+ "&videoURL="
						+ mSecondVideoDetailInfo.getVideo().getUrl();
			}
			String content = "\""
					+ mSecondVideoDetailInfo.getVideo().getTitle()
					+ "\""
					+ "点此播放"
					+ "\""
					+ url
					+ "\""
					+ "（通过＃第一视频＃分享，@第一视频，聚合全球海量有趣有料有用的精选短视频，助你大开眼界！下载猛戳http://apps.v1.cn）";
			ShareParams sp = new ShareParams();
			sp.setShareType(Platform.SHARE_IMAGE);
			sp.setTitle(mSecondVideoDetailInfo.getVideo().getTitle());
			sp.setTitleUrl(url);
			sp.setText(content);
			sp.setImageUrl(mSecondVideoDetailInfo.getVideo().getPic());
			plat.setPlatformActionListener(new SharePlatformActionListener(
					this, null));
			plat.share(sp);
		} else {
			showToast("未获取到分享内容");
		}
	}

	/**
	 * 分享弹出框
	 * 
	 * @param context
	 * @param type
	 *            0:新浪，1，腾讯微博 2，两个一起
	 */
	private void showSharedDialog(final Context context, final int type) {
		if (mSecondVideoDetailInfo == null
				|| mSecondVideoDetailInfo.getVideo() == null) {
			showToast("未获取到分享内容");
			return;
		}
		String url = "";
		if (!TextUtils.isEmpty(mSecondVideoDetailInfo.getShareUrl())
				&& mSecondVideoDetailInfo.getShareUrl().length() > 6) {
			url = mSecondVideoDetailInfo.getShareUrl();
		} else {
			url = Constant.PAIKE_VIDEO_SHARE_URL
					+ mSecondVideoDetailInfo.getVideo().getPic() + "&videoURL="
					+ mSecondVideoDetailInfo.getVideo().getUrl();
		}
		String content = "\""
				+ mSecondVideoDetailInfo.getVideo().getTitle()
				+ "\""
				+ "点此播放"
				+ "\""
				+ url
				+ "\""
				+ "（通过＃第一视频＃分享，@第一视频，聚合全球海量有趣有料有用的精选短视频，助你大开眼界！下载猛戳http://apps.v1.cn）";
		View shareView = View.inflate(context, R.layout.dialog_one_key_share,
				null);
		final Dialog dialog = new Dialog(context, R.style.dialog_custom);
		Display display = this.getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		LayoutParams params = new LayoutParams((int) (width * 0.9),
				ViewGroup.LayoutParams.MATCH_PARENT);
		dialog.setContentView(shareView, params);
		dialog.setCancelable(true);

		final EditText contentEt = (EditText) shareView
				.findViewById(R.id.tv_shared_content);
		final TextView contentNum = (TextView) shareView
				.findViewById(R.id.tv_content_num);

		final View sinaSelect = shareView.findViewById(R.id.rl_sina);
		final View qqSelect = shareView.findViewById(R.id.rl_qq_share);
		contentEt.setText(content);
		if (type == 0) {
			qqSelect.setVisibility(View.GONE);
		} else if (type == 1) {
			sinaSelect.setVisibility(View.GONE);
		}
		if (!content.equals("")) {
			String number = Utils.calculateLength(content) + "/"
					+ BaseActivity.TEXT_LENGTH;
			contentNum.setText(number);
		} else {
			contentNum.setText("0/" + BaseActivity.TEXT_LENGTH);
		}

		contentEt.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int selectionStart;
			private int selectionEnd;

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				temp = s;
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				String number = Utils.calculateLength(s) + "/"
						+ BaseActivity.TEXT_LENGTH;
				contentNum.setText(number);
				selectionStart = contentEt.getSelectionStart();
				selectionEnd = contentEt.getSelectionEnd();
				if (Utils.calculateLength(temp) > BaseActivity.TEXT_LENGTH) {
					s.delete(
							(selectionStart - (int) (Utils.calculateLength(s) - BaseActivity.TEXT_LENGTH)),
							selectionEnd);
					contentEt.setText(s);
					contentEt.setSelection(selectionStart);// 设置光标
				}
			}
		});

		shareView.findViewById(R.id.tv_share).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						String contentStr = contentEt.getText().toString()
								.trim();
						if (!TextUtils.isEmpty(contentStr)) {
							onkeyshare(v, ShareSDK.getPlatform(
									SecondVideoDetailActivity2.this,
									SinaWeibo.NAME), contentStr);
							dialog.dismiss();

						} else {
							showToast(R.string.share_content_not_null);
						}
					}
				});
		shareView.findViewById(R.id.close_account_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
		shareView.findViewById(R.id.iv_cleanup).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						contentEt.setText("");
						contentNum.setText("0/" + BaseActivity.TEXT_LENGTH);
					}
				});

		dialog.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss(DialogInterface dialog) {
				// isCanPlay = true;
			}
		});
		dialog.show();
	}

	/**
	 * sina微博
	 * 
	 * @param plat
	 * @param content
	 */
	private void onkeyshare(View v, Platform plat, String content) {
		if (mSecondVideoDetailInfo != null
				&& mSecondVideoDetailInfo.getVideo() != null) {
			ShareParams sp = new ShareParams();
			sp.setShareType(Platform.SHARE_IMAGE);
			sp.setTitle(mSecondVideoDetailInfo.getVideo().getTitle());
			sp.setText(content);
			sp.setImageUrl(mSecondVideoDetailInfo.getVideo().getPic()); // 直接分享网络地址
			plat.setPlatformActionListener(new SharePlatformActionListener(
					this, null));
			plat.share(sp);
		} else {
			showToast("未获取到标题");
		}
	}

}
